#include "cursor.h"
#include "logger.h"
void InitializeCursorSpace()
{
    int i = 0;
    for (i = 0; i < SpaceSize; i++)
    {
        CursorSpace[i].Next = i + 1;
        CursorSpace[i].Element = 0;
    }
    CursorSpace[i].Next = 0;
}

Position CursorAlloc(void)
{
    Position P;
    //选取空闲链表中的下一个节点
    P = CursorSpace[0].Next;
    CursorSpace[0].Next = CursorSpace[P].Next;
    CursorSpace[P].Next = 0;
    return P;
}
void CursorFree(Position P)
{
    CursorSpace[P].Next = CursorSpace[0].Next;
    CursorSpace[0].Next = P;
}

Position Find(ElementType X, List L)
{
    Position P;
    //L为表头
    P = CursorSpace[L].Next;
    while (P && CursorSpace[P].Element != X)
    {
        P = CursorSpace[P].Next;
    }
    return P;
}

//返回前一个元素的位置，如果前面没有元素，则返回当前位置
Position FindPrevious(ElementType X, List L)
{
    Position Pre;
    Position P;
    Pre = P;
    P = CursorSpace[L].Next;
    while (P && CursorSpace[P].Element != X)
    {
        Pre = P;
        P = CursorSpace[P].Next;
    }
    return Pre;
}

int IsEmpty(List L)
{
    return CursorSpace[L].Next == 0;
}

int IsLast(Position P, List L)
{
    return CursorSpace[P].Next == 0;
}

void Delete(ElementType X, List L)
{
    Position P, Tmp;

    if (!IsEmpty(L))
    {
        P = FindPrevious(X, L);
        Tmp = CursorSpace[P].Next;
        CursorSpace[P].Next = CursorSpace[Tmp].Next;
        CursorFree(Tmp);
    }
}

void Insert(ElementType X, List L, Position P)
{
    Position tmp = CursorAlloc();
    if (!tmp)
        FatalError("Out of space!");
    CursorSpace[tmp].Element = X;
    CursorSpace[tmp].Next = CursorSpace[P].Next;
    CursorSpace[P].Next = tmp;
}

void Print(List L)
{
    Position P = CursorSpace[L].Next;
    while (P)
    {
        printf("%d ", CursorSpace[P].Element);
        P = CursorSpace[P].Next;
    }
    printf("\n");
}
